<template>
  <div>
    <!-- 搜索 -->
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      v-show="hidden"
    >
      <el-form-item label="属性名称">
        <el-input
          v-model="formInline.propName"
          placeholder="请输入属性名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchFun" icon="el-icon-search"
          >搜索</el-button
        >
        <el-button type="danger" @click="clearFun" icon="el-icon-delete"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 新增 -->
    <div class="add">
      <el-button type="primary" @click="addFun">+ 新增</el-button>
      <div class="right">
        <el-button type="text" icon="el-icon-refresh"></el-button>
        <el-button
          type="text"
          icon="el-icon-search"
          @click="hiddenSearch"
        ></el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      v-loading="listLoading"
    >
      <el-table-column type="index" label="序号" width="180"> </el-table-column>
      <el-table-column prop="propName" label="属性名称" width="180">
      </el-table-column>
      <el-table-column label="属性值" prop="prodPropValues">
        <template slot-scope="scope">
          <el-tag
            v-for="propValue in scope.row.propValue"
            :key="propValue"
            class="tag"
          >
            {{ propValue }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            @click="editFun(scope.row)"
            type="primary"
            size="small"
            icon="el-icon-edit "
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="delFun(scope.row)"
            icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <el-dialog title="新增/编辑" :visible.sync="dialogTableVisible">
      <el-form>
        <el-table :data="modalTableData" style="width: 100%">
          <el-table-column label="属性名称" width="150">
            <template slot-scope="scope">
              <el-input
                type="text"
                placeholder="请输入属性名称"
                v-model="scope.row.propName"
                maxlength="10"
                show-word-limit
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="属性值">
            <template slot-scope="scope">
              <el-tag
                :key="tag"
                v-for="tag in scope.row.prodPropValues"
                closable
                :disable-transitions="false"
                @close="handleClose(scope.row, tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                maxlength="10"
                show-word-limit
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right; margin-top: 20px">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <!-- 新增 -->
          <el-button type="primary" @click="saveModalData" v-if="show"
            >确定</el-button
          >
          <!-- 编辑 -->
          <el-button type="primary" @click="editModalData" v-else
            >确定</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  addList,
  editList,
  searchList,
  delList,
} from "@/api/cpgl/prod-spec";
export default {
  data() {
    return {
      formInline: {}, //搜索框
      tableData: [], //表格
      dialogTableVisible: false, //新增标签模态框开关
      modalTableData: [
        {
          propName: "", // 属性名称
          prodPropValues: [], // 属性值（标签列表）
        }, // 初始行数据
      ],
      inputVisible: false, // 是否显示输入框
      inputValue: "",
      show: true, //新增编辑开关
      propId: null, //编辑id
      currentPage: 1, // 当前页码
      total: 0, // 总条数
      page: 10, // 每页条数
      flag: true, //判断是否为搜索
      hidden: true, //隐藏新增按钮
      listLoading: false,
    };
  },
  created() {
    this.fetchData();
  },
  mounted() {
    setTimeout(() => {
      this.fetchData();
    }, 2000); // 延迟2秒加载
  },
  methods: {
    // 表格
    fetchData() {
      this.listLoading = true;
      console.log(Date.now());
      const queryParams = {
        t: Date.now(),
        current: this.currentPage,
        size: this.page,
      };
      getList(queryParams).then((response) => {
        console.log(response);
        (this.total = response.data.total), // 总条数
          (this.tableData = response.data.records.map((item) => ({
            ...item,
            propValue: item.prodPropValues.map(
              (prodPropValues) => prodPropValues.propValue
            ),
          })));
        this.listLoading = false;
      });
      // .catch((error) => {
      //   console.error("接口请求失败：", error);
      //   this.$message.error("加载数据失败，请重试！");
      //   // 重试机制（例如3秒后重新请求）
      //   setTimeout(() => {
      //     this.fetchData();
      //   }, 3000);
      // });
      console.log(this.tableData);
    },

    // 搜索
    searchFun() {
      this.listLoading = true;
      if (this.flag) {
        this.currentPage = 1;
        this.flag = false;
      }
      const queryParams = {
        t: Date.now(),
        current: this.currentPage,
        size: this.page,
        propName: this.formInline.propName,
      };
      searchList(queryParams).then((response) => {
        console.log(response);
        (this.total = response.data.total), // 总条数
          (this.tableData = response.data.records.map((item) => ({
            ...item,
            propValue: item.prodPropValues.map(
              (prodPropValues) => prodPropValues.propValue
            ),
          })));
        this.listLoading = false;
      });
    },
    // 清空
    clearFun() {
      this.formInline.propName = "";
    },

    hiddenSearch() {
      this.hidden = !this.hidden;
    },
    // 新增
    addFun() {
      this.dialogTableVisible = true;
      this.show = true;
      this.modalTableData = [
        {
          propName: "", // 属性名称
          prodPropValues: [], // 属性值（标签列表）
        },
      ];
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 点击保存
    saveModalData() {
      this.dialogTableVisible = false;
      const requestData = {
        t: Date.now(),
        propName: this.modalTableData[0].propName, // 属性名称
        prodPropValues: this.modalTableData[0].prodPropValues.map((value) => ({
          propValue: value, // 属性值
          // valueId: this.prodPropValues.length + 1, // 自动生成 valueId
        })),
      };
      console.log(requestData);
      addList(requestData).then((response) => {
        console.log(response.code);
        if (response.code === "00000") {
          this.listLoading = false;
          this.$message({
            message: "新增成功",
            type: "success",
          });
        } else {
          this.$message({
            message: response.msg,
            type: "error",
          });
        }
      });
      if (this.formInline.propName) {
        this.searchFun();
      } else {
        this.fetchData();
        console.log(2);
      }
    },
    // 删除标签
    handleClose(row, tag) {
      row.prodPropValues.splice(row.prodPropValues.indexOf(tag), 1);
      row.prodPropValues = row.prodPropValues.filter(
        (item) => item.prodPropValues !== tag
      );
    },
    // 获取焦点时
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput && this.$refs.saveTagInput.focus();
      });
    },
    // 失去焦点后
    handleInputConfirm(row) {
      let inputValue = this.inputValue.trim();
      if (inputValue) {
        row.prodPropValues.push(inputValue);
        // this.prodPropValues.push({
        //   valueId: this.prodPropValues.length, // 自动生成 valueId
        //   prodPropValues: inputValue,
        // });
        // console.log(this.prodPropValues);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    // 编辑
    editFun(row) {
      this.show = false;
      console.log(row);
      this.dialogTableVisible = true;
      (this.propId = row.propId),
        (this.modalTableData = [
          {
            propName: row.propName, // 属性名称
            prodPropValues: row.propValue, // 属性值（标签列表）
          },
        ]);
      this.inputVisible = false;
    },
    // 点击保存
    editModalData() {
      this.dialogTableVisible = false;
      console.log(this.modalTableData);
      const requestData = {
        propId: this.propId,
        t: Date.now(),
        propName: this.modalTableData[0].propName, // 属性名称
        prodPropValues: this.modalTableData[0].prodPropValues.map((value) => ({
          propValue: value, // 属性值
          // valueId: this.prodPropValues.length + 1, // 自动生成 valueId
        })),
      };
      console.log(requestData);
      editList(requestData).then((response) => {
        console.log(response);
        if (response.code === "00000") {
          this.listLoading = false;
          this.$message({
            message: "修改成功",
            type: "success",
          });
          if (this.formInline.propName) {
            this.searchFun();
          } else {
            this.fetchData();
          }
        } else {
          this.$message({
            message: response.msg,
            type: "error",
          });
        }
      });
    },
    // 删除
    delFun(row) {
      console.log(row.propId);
      this.$confirm("确认进行删除操作？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delList([row.propId]).then((response) => {
            console.log(response);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.fetchData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = val;
      if (this.formInline.propName) {
        this.searchFun();
      } else {
        this.fetchData();
      }
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      if (this.formInline.propName) {
        this.searchFun();
      } else {
        this.fetchData();
      }
    },
  },
};
</script>

<style scoped>
::v-deep .el-table .cell {
  display: flex;
  justify-content: center;
}
::v-deep .el-tag {
  margin: 0 5px;
}
.add {
  display: flex;
  justify-content: space-around;
}
.add .right {
  width: 100px;
  display: flex;
  justify-content: space-around;
}
</style>
